
#include "rtmp_server.h"
#include "rtmp_connection.h"/* m_server->OnConnectionCallback() */
#include <cstdint>
#include <memory>

RtmpServer::RtmpServer():m_loop(EPOLL)
{

}

void RtmpServer::RunRtmpServer(int listen_port)
{
    m_server = std::make_shared<Server>(&m_loop);

    m_server->OnConnectionCallback([this](std::shared_ptr<Connection> conn){
            
        int64_t index = conn->Index();
        m_client_conn_map[index] = std::make_shared<RtmpConnection>(conn);
    });
    m_server->OnDisConnectionCallback([this](std::shared_ptr<Connection> conn){

        auto iter = m_client_conn_map.find(conn->Index());
        if (iter != m_client_conn_map.end())
        {
			INFO("remove connection : {}", iter->second->Index());
            iter->second->Remove();
            m_client_conn_map.erase(iter);
        }
    });
    m_server->OnMessageCallback([this](std::shared_ptr<Connection> conn, std::shared_ptr<SocketBuffer> buffer){
            
        auto iter = m_client_conn_map.find(conn->Index());
        if (iter != m_client_conn_map.end())
        {   
            int length = iter->second->PushRtmpData(buffer->GetBufferData(), buffer->GetBufferLength());
            buffer->FreeBufferData(length);
        }
    });

    m_server->ListenServer(listen_port);

    m_loop.Run();
}
